package com.ruoyi.common.utils.poi;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * Word 相关处理
 * @author ysz
 *
 */
public class WordUtil {
    private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);

    /**
     * 默认编码
     */
    private String CharacterEncoding = "utf-8";

    /**
     * 文档对象
     */
    private XWPFDocument document;

    /**
     * 段落对象
     */
    private XWPFParagraph paragraph;

    /**
     * 实例
     */
    private XWPFRun run;

    /**
     * 初始化 word 文档
     */
    public void init() {
        this.document = new XWPFDocument();
        this.paragraph = document.createParagraph();
        this.run = paragraph.createRun();
    }

    /**
     * 添加图片
     * @param pictureSrc
     * @param width
     * @param height
     * @throws IOException
     * @throws InvalidFormatException
     */
    public void addPicture(String pictureSrc, int width, int height) throws IOException, InvalidFormatException {
        run.addPicture(new FileInputStream(pictureSrc),
                XWPFDocument.PICTURE_TYPE_PNG,
                pictureSrc,
                Units.toEMU(width),
                Units.toEMU(height));
    }

    /**
     * 添加图片 批量
     * @param pictureSrc
     * @param width
     * @param height
     * @throws IOException
     * @throws InvalidFormatException
     */
    public void addPictures(String[] picturesSrc, int width, int height) throws IOException, InvalidFormatException {
        for (String pictureSrc : picturesSrc) {
            run.addPicture(new FileInputStream(pictureSrc),
                    XWPFDocument.PICTURE_TYPE_PNG,
                    pictureSrc,
                    Units.toEMU(width),
                    Units.toEMU(height));
        }
    }

    /**
     * 填充文本
     * @param text
     */
    public void setText(String text) {
        run.setText(text);
    }

    /**
     * 通过字节流导出 doc/docx，可在客户端进行下载
     * @param fileName
     * @param response
     */
    public void exportWord(String fileName, HttpServletResponse response) {
        response.reset();
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding(CharacterEncoding);

        try {
            document.write(response.getOutputStream());
        } catch (IOException e) {
            log.error("导出Word异常{}", e.getMessage());
            throw new RuntimeException("导出异常，请联系管理员");
        } finally {
            IOUtils.closeQuietly(document);
        }
    }
}
